<script setup lang="ts">
import { useGuessList } from '@/composables';
import {
  deleteMemberOrderByIdAPI,
  getMemberOrderByIdAPI,
  getMemberOrderConsignmentByIdAPI,
  getMemberOrderLogisticsByIdAPI,
  getMemberOrderReceiptByIdAPI,
  putMemberOrderCancelByIdAPI,
} from '@/services/order';
import type { LogisticItem, OrderResult } from '@/types/order';
import { onLoad, onReady } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { OrderState, OrderStateList } from '@/services/constants';
import pageSkeleton from './components/pageSkeleton.vue';
import { getPayMockAPI, getPayWxPayMiniPayAPI } from '@/services/pay';

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// 猜你喜欢
const { guessRef, onScrolltolower } = useGuessList();
// 弹出层组件
const popup = ref<UniHelper.UniPopupInstance>();
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
]);
// 订单取消原因
const reason = ref('');
// 复制内容
const onCopy = (id: string) => {
  // 设置系统剪贴板的内容
  uni.setClipboardData({ data: id });
};
// 获取页面参数
const query = defineProps<{
  id: string;
}>();

// 获取页面路径参数
const pages = getCurrentPages();
// 获取当前页面实例
const pageInstance = pages.at(-1) as any;
// 页面渲染完成，绑定关键帧动画
onReady(() => {
  // 动画效果,导航栏背景色
  pageInstance.animate(
    '.navbar',
    [
      {
        backgroundColor: 'transparent',
      },
      {
        backgroundColor: '#f8f8f8',
      },
    ],
    1000,
    {
      scrollSource: '#scroller',
      timeRange: 1000,
      startScrollOffset: 0,
      endScrollOffset: 50,
    }
  );
  // 动画效果,导航栏标题
  pageInstance.animate(
    '.navbar .title',
    [
      {
        color: '#transparent',
      },
      {
        color: '#000',
      },
    ],
    1000,
    {
      scrollSource: '#scroller',
      timeRange: 1000,
      startScrollOffset: 0,
      endScrollOffset: 50,
    }
  );
  // 动画效果,导航栏返回按钮
  pageInstance.animate(
    '.navbar .back',
    [
      {
        color: 'transparent',
      },
      {
        color: '#000',
      },
    ],
    1000,
    {
      scrollSource: '#scroller',
      timeRange: 1000,
      startScrollOffset: 0,
      endScrollOffset: 50,
    }
  );
});
// 获取订单详情数据
const orderDetail = ref<OrderResult>();
const getMemberOrderByIdData = async () => {
  const res = await getMemberOrderByIdAPI(query.id);
  orderDetail.value = res.result;
  //仅在订单状态为待收货，待评价，已完成时，可获取物流信息
  if (
    [
      OrderState.DaiShouHuo,
      OrderState.DaiPingJia,
      OrderState.YiWanCheng,
    ].includes(orderDetail.value.orderState)
  ) {
    getMemberOrderLogisticsByIdData();
  }
};
// 获取订单物流信息
const logisticsList = ref<LogisticItem[]>([]);
const getMemberOrderLogisticsByIdData = async () => {
  const res = await getMemberOrderLogisticsByIdAPI(query.id);
  logisticsList.value = res.result.list;
};
// 初始化调用
onLoad(() => {
  getMemberOrderByIdData();
});
// 支付倒计时结束
const onTimeUp = () => {
  // 修改订单状态为已取消
  orderDetail.value!.orderState = OrderState.YiQuXiao;
};
// 订单支付
const onPayment = async () => {
  // 通过环境变量区分开发环境
  if (import.meta.env.DEV) {
    // 开发环境：模拟支付，修改订单状态为已支付
    await getPayMockAPI({ orderId: query.id });
  } else {
    // #ifdef MP-WEIXIN
    const res = await getPayWxPayMiniPayAPI({ orderId: query.id });
    await wx.requestPayment(res.result);
    // #endif
  }
  // 关闭当前页，再跳转支付结果页
  uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${query.id}` });
};

// 是否为开发环境
const isDev = import.meta.env.DEV;
// 模拟发货
const onOrderSend = async () => {
  if (isDev) {
    await getMemberOrderConsignmentByIdAPI(query.id);
    uni.showToast({
      title: '模拟发货成功',
      icon: 'success',
    });
    // 主动更新订单状态
    orderDetail.value!.orderState = OrderState.DaiShouHuo;
  }
};
// 确认收货
const onOrderComfirm = () => {
  // 二次确认弹窗
  uni.showModal({
    content: '为保障您的权益，请收到货并确认后，在确认后货！',
    confirmColor: '#ec602b',
    success: async (success) => {
      if (success.confirm) {
        const res = await getMemberOrderReceiptByIdAPI(query.id);
        // 更新订单状态
        orderDetail.value = res.result;
      }
    },
  });
};

// 删除订单
const onDeleteOrder = () => {
  uni.showModal({
    content: '确认要删除该订单吗？',
    confirmColor: '#ec602b',
    success: async (success) => {
      if (success.confirm) {
        uni.showLoading({ title: '加载中...' });
        await deleteMemberOrderByIdAPI({ ids: [query.id] });
        uni.hideLoading();
        // 关闭当前页面，跳转到订单列表
        uni.redirectTo({ url: '/pagesOrder/list/list?type=0' });
      }
    },
  });
};
// 取消订单
const onOrderCancle = async () => {
  const res = await putMemberOrderCancelByIdAPI(query.id, {
    cancelReasonL: reason.value,
  });
  // 更新订单状态
  orderDetail.value = res.result;
  // 关闭弹窗
  popup.value?.close!();
  // 轻提示
  uni.showToast({ icon: 'none', title: '订单取消成功' });
};
</script>

<template>
  <!-- 自定义导航栏: 默认透明不可见, scroll-view 滚动到 50 时展示 -->
  <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
    <view class="wrap">
      <navigator
        v-if="pages.length > 1"
        open-type="navigateBack"
        class="back icon-left"
      ></navigator>
      <navigator
        v-else
        url="/pages/index/index"
        open-type="switchTab"
        class="back icon-home"
      >
      </navigator>
      <view class="title">订单详情</view>
    </view>
  </view>
  <scroll-view
    scroll-y
    class="viewport"
    id="scroller"
    @scrolltolower="onScrolltolower"
  >
    <template v-if="orderDetail">
      <!-- 订单状态 -->
      <view
        class="overview"
        :style="{ paddingTop: safeAreaInsets!.top + 20 + 'px' }"
      >
        <!-- 待付款状态:展示去支付按钮和倒计时 -->
        <template v-if="orderDetail?.orderState === OrderState.DaiFuKuan">
          <view class="status icon-clock">等待付款</view>
          <view class="tips">
            <text class="money"
              >应付金额: ¥ {{ orderDetail.payMoney.toFixed(2) }}</text
            >
            <text class="time">支付剩余</text>
            <!-- 倒计时组件 -->
            <uni-countdown
              :second="orderDetail.countdown"
              color="#fff"
              splitor-color="#fff"
              :show-day="false"
              :show-colon="false"
              @timeup="onTimeUp"
            />
          </view>
          <view class="button" @tap="onPayment">去支付</view>
        </template>
        <!-- 其他订单状态:展示再次购买按钮 -->
        <template v-else>
          <!-- 订单状态文字 -->
          <view class="status">
            {{ OrderStateList[orderDetail.orderState].text }}
          </view>
          <view class="button-group">
            <navigator
              class="button"
              :url="`/pagesOrder/create-order/create-order?orderId=${query.id}`"
              hover-class="none"
            >
              再次购买
            </navigator>
            <!-- 待发货状态：模拟发货,开发期间使用,用于修改订单状态为已发货 -->
            <view
              v-if="isDev && orderDetail.orderState == OrderState.DaiFaHuo"
              class="button"
              @tap="onOrderSend"
            >
              模拟发货
            </view>
          </view>
        </template>
      </view>
      <!-- 配送状态 -->
      <view class="shipment">
        <!-- 订单物流信息 -->
        <view v-for="item in logisticsList" :key="item.id" class="item">
          <view class="message">
            {{ item.text }}
          </view>
          <view class="date"> {{ item.time }} </view>
        </view>
        <!-- 用户收货地址 -->
        <view class="locate">
          <view class="user">
            {{ orderDetail.receiverContact }} {{ orderDetail.receiverMobile }}
          </view>
          <view class="address"> {{ orderDetail.receiverAddress }} </view>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="goods">
        <view class="item">
          <navigator
            class="navigator"
            v-for="item in orderDetail.skus"
            :key="item.id"
            :url="`/pages/goods/goods?id=${item.spuId}`"
            hover-class="none"
          >
            <image class="cover" :src="item.image"></image>
            <view class="meta">
              <view class="name ellipsis">{{ item.name }}</view>
              <view class="type">{{ item.attrsText }}</view>
              <view class="price">
                <view class="actual">
                  <text class="symbol">¥</text>
                  <text>{{ item.curPrice.toFixed(2) }}</text>
                </view>
              </view>
              <view class="quantity">x{{ item.quantity }}</view>
            </view>
          </navigator>
          <!-- 待评价状态:展示按钮 -->
          <view
            class="action"
            v-if="orderDetail.orderState === OrderState.DaiPingJia"
          >
            <view class="button primary">申请售后</view>
            <navigator url="" class="button"> 去评价 </navigator>
          </view>
        </view>
        <!-- 合计 -->
        <view class="total">
          <view class="row">
            <view class="text">商品总价: </view>
            <view class="symbol">{{ orderDetail.totalMoney.toFixed(2) }}</view>
          </view>
          <view class="row">
            <view class="text">运费: </view>
            <view class="symbol">{{ orderDetail.postFee.toFixed(2) }}</view>
          </view>
          <view class="row">
            <view class="text">应付金额: </view>
            <view class="symbol primary">{{
              orderDetail.payMoney.toFixed(2)
            }}</view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="detail">
        <view class="title">订单信息</view>
        <view class="row">
          <view class="item">
            订单编号: {{ query.id }}
            <text class="copy" @tap="onCopy(query.id)">复制</text>
          </view>
          <view class="item">下单时间: {{ orderDetail.createTime }}</view>
        </view>
      </view>

      <!-- 猜你喜欢 -->
      <online-guess ref="guessRef"></online-guess>

      <!-- 底部操作栏 -->
      <view
        class="toolbar-height"
        :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
      ></view>
      <view
        class="toolbar"
        :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
      >
        <!-- 待付款状态:展示支付按钮 -->
        <template v-if="orderDetail.orderState === OrderState.DaiFuKuan">
          <view class="button primary" @tap="onPayment"> 去支付 </view>
          <view class="button" @tap="popup?.open?.()"> 取消订单 </view>
        </template>
        <!-- 其他订单状态:按需展示按钮 -->
        <template v-else>
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create-order/create-order?orderId=${query.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view
            class="button primary"
            v-if="orderDetail.orderState === OrderState.DaiShouHuo"
            @tap="onOrderComfirm"
          >
            确认收货
          </view>
          <!-- 待评价状态: 展示去评价 -->
          <view
            class="button"
            v-if="orderDetail.orderState === OrderState.DaiPingJia"
            >去评价
          </view>
          <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
          <view
            class="button delete"
            v-if="orderDetail.orderState >= OrderState.DaiPingJia"
            @tap="onDeleteOrder"
          >
            删除订单
          </view>
        </template>
      </view>
    </template>
    <!-- 骨架屏组件 -->
    <pageSkeleton v-else />
  </scroll-view>
  <!-- 取消订单弹窗 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <view class="popup-root">
      <view class="title">订单取消</view>
      <view class="description">
        <view class="tips">请选择取消订单的原因：</view>
        <view
          class="cell"
          v-for="item in reasonList"
          :key="item"
          @tap="reason = item"
        >
          <text class="text">{{ item }}</text>
          <text class="icon" :class="{ checked: item === reason }"></text>
        </view>
      </view>
      <view class="footer">
        <view class="button" @tap="popup?.close?.()">取消</view>
        <view class="button primary" @tap="onOrderCancle">确认</view>
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss">
@import './components/styles/detail.scss';
page {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.navbar {
  width: 750rpx;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  /* background-color: #f8f8f8; */
  background-color: transparent;

  .wrap {
    position: relative;

    .title {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      /* color: #000; */
      color: transparent;
    }

    .back {
      position: absolute;
      left: 0;
      height: 44px;
      width: 44px;
      font-size: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      /* color: #000; */
      color: #fff;
    }
  }
}

.viewport {
  height: 100vh;
  background-color: #f7f7f8;
}
</style>
